var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

// 引入验证token工具文件
var utils = require('./utils/index');

// express项目路由文件
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var bannerRouter = require('./routes/banner');

// vue接口
var addressApi = require('./api/address');
var bannerApi = require('./api/banner');
var cartApi = require('./api/cart');
var orderApi = require('./api/order');
var proApi = require('./api/pro');
var payApi = require('./api/pay');
var searchApi = require('./api/search');
var userApi = require('./api/user');

// react后台管理系统接口
var proReact = require('./react/pro')
var cartReact = require('./react/cart')
var adminReact = require('./react/admin')

var app = express();

// 自定义中间件 ---  解决跨域问题
var allowCrossDomain = (req, res, next) => {
  // get req.query post req.body
  // res
  // 所有接口均可以访问服务器
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', '*')
  next()
}
// 使用自定义跨域中间件
app.use(allowCrossDomain)

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// vue接口注册
app.use('/api/address', addressApi);
app.use('/api/banner', bannerApi);
app.use('/api/cart', cartApi);
app.use('/api/order', orderApi);
app.use('/api/pro', proApi);
app.use('/api/pay', payApi);
app.use('/api/search', searchApi);
app.use('/api/user', userApi);

// 注册react后台管理系统的所有路由
// 1.匹配完整路径app.all 接受正则,请求路径必须完全匹配
// 2.在进行路由匹配的时候不限定方法，什么请求方法都可以
app.all('/react/*', (req, res, next) => {
  if (req.url === '/react/admin/login') {
    next() // 登录接口不验证token
  } else {
    utils.validateReactToken(req, res).then(() => {
      next() // 走后续的接口
    })
  }
})


// react后台管理系统接口注册
app.use('/react/pro', proReact)
app.use('/react/cart', cartReact)
app.use('/react/admin', adminReact)

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/banner', bannerRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
